﻿using HW_CommunicationLib.Base;
using HW_CommunicationLib.Enums;
using HW_CommunicationLib.Model;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO.Ports;
using System.Linq;
using System.Net.Sockets;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace HW_CommunicationLib
{
    ///<summary>
    ///描述: 下位机通信接口实例
    ///作者: 孙小同
    ///创建时间: 2024/6/10 21:06:48
    ///</summary>
    public class Communication : CommunicationBase
    {
        private IPAddress iPAddress = null;
        private int netPort = 0;

        private CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();

        public event Action<object, CommunicationArgsBase> OnError;
        public event Action<object, DataPackage> OnReceived;

        /// <summary>
        /// 网口通讯模式初始化
        /// </summary>
        /// <param name="ipAddress"></param>
        /// <param name="netPort"></param>
        public void Initiallize(IPAddress ipAddress, int netPort)
        {
            this.iPAddress = ipAddress;
            this.netPort = netPort;
            CommunicationMode = Enums.CommunicationMode.TCP;
            TcpClient = new System.Net.Sockets.TcpClient();
        }
        public ConnectionResult Connect(bool reConnect = false)
        {
            ConnectionResult connectionResult = new ConnectionResult();
            switch (CommunicationMode)
            {
                case Enums.CommunicationMode.TCP:
                    try
                    {
                        if (reConnect)
                        {
                            TcpClient = new TcpClient();
                        }
                        TcpClient.Connect(iPAddress, netPort);//连接TCP
                        connectionResult.Message = "连接成功";
                        connectionResult.Success = true;
                    }
                    catch (Exception ex)
                    {
                        connectionResult.Exception = ex;
                        connectionResult.Message = "连接失败";
                        connectionResult.Success = false;
                    }
                    break;
                default: break;
            }
            return connectionResult;
        }

        public override bool Start()
        {
            switch (CommunicationMode)
            {
                case Enums.CommunicationMode.TCP:
                    try
                    {
                        Task.Factory.StartNew(Receive);//接收TCP数据
                        return true;
                    }
                    catch (Exception ex)
                    {
                        OnError?.Invoke(this, new CommunicationArgsBase { Exception = ex, Message = "接收TCP数据发生错误" });

                        return false;
                    }
                default: break;
            }
            return false;
        }

        private void Receive()
        {
            //todo 接收监听
        }

        public override DataPackage Send(DataPackage dataPackage)
        {
                        try
                        {
                            if(TcpClient != null && TcpClient.Connected) {
                            NetworkStream DataSend = TcpClient.GetStream();                          //定义网络流
                            DataSend.Write(dataPackage.SendBuffer, 0, dataPackage.SendBuffer.Length);//发送通讯数据
                            byte[] bytes = new byte[dataPackage.NeedLength];
                            DataSend.Read(bytes, 0, bytes.Length);     //读取返回数据
                            dataPackage.ReceiveBuffer = bytes;
                            return dataPackage;
                            }
                            Exception ex = new Exception();
                            return dataPackage;
                        }
                        catch (Exception ex)
                        {
                            
                            OnError?.Invoke(this, new CommunicationArgsBase { Exception = ex, Message = "发送tcp数据时发生错误" });
                            return dataPackage;
                        }
                   
        }

        public override bool Stop()
        {
            cancellationTokenSource.Cancel();
            TcpClient.Close();
            return true;
        }
    }
}
